﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;

namespace VSM.Parts
{
    public partial class AdvancePayment : System.Web.UI.Page
    {
        #region Fields
        private  GeneralFunctions GF = null;
        private string TblHeaderName = "ORCT";
        private string TblLineName = "tbl_RDR1";
        private string HeaderKeyName = "DocEntry";
        private string CurrentPageUrl = "/Business/Parts/Sales/AdvancePayment.aspx";
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session[Utils.AppConstants.ID_User] == null
                    || Session[Utils.AppConstants.Password] == null
                    || Session[Utils.AppConstants.ID_Dealer] == null)
                {
                    Response.Redirect("../../../Login.aspx");
                }
                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                if (dbType != "VSM")
                {
                    this.txtACRDate.Visible = false;
                    this.txtPACR.Visible = false;
                    this.lblacr.Visible = false;
                    this.lblacrDate.Visible = false;
                }
                if (!IsPostBack)
                {
                    ClearScreen();

                    this.txtACRDate.Text = DateTime.Now.Date.ToString(Utils.AppConstants.DATE);

                    String incPmtId = Request.QueryString["incPmt_id"];
                    if (!String.IsNullOrEmpty(incPmtId))
                    {
                        LoadData(incPmtId, ConvertDocType.Get2String(DocType.INCOMING));
                        SetScreenStatus("Update");
                    }
                    else
                    {
                        LoadDefault();
                        SetScreenStatus("New");
                    }
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["TblRDR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text );
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    this.grvSO.EditIndex = -1;
                    BindData((DataTable)Session["TblRDR1Table"]);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void chkSelected_CheckedChanged(object sender, EventArgs e)
        {
            DataTable tblRDR1 = (DataTable)Session["TblRDR1Table"];
            GridViewRow row = (GridViewRow)((DataControlFieldCell)((CheckBox)sender).Parent).Parent;
            Label lblNo = (Label)row.FindControl("lblNo");
            if (tblRDR1 != null)
            {
                DataRow[] rupdate = tblRDR1.Select("No='" + lblNo.Text.Trim() + "'");
                if (rupdate.Length > 0)
                {
                    
                    HiddenField hdnRemainOrg = (HiddenField)row.FindControl("hdnRemainOrg");
                    HiddenField hdnCardCode = (HiddenField)row.FindControl("hdnCardCode");
                    Double dblRemain = Double.Parse(string.IsNullOrEmpty(hdnRemainOrg.Value) ? "0" : GF.ResetFormatNumeric(hdnRemainOrg.Value));
                    Double TotalPayment = Double.Parse(string.IsNullOrEmpty(txtCustRemain.Text.Trim()) ? "0" : GF.ResetFormatNumeric(txtCustRemain.Text.Trim()));
                    Double CustRemainTemp = 0;

                    if (!((CheckBox)row.FindControl("chkSelected")).Checked) // De-selection payment
                    {
                        Double dblPaid = Double.Parse(string.IsNullOrEmpty(((TextBox)row.FindControl("txtPaid")).Text ) ? "0" : GF.ResetFormatNumeric(((TextBox)row.FindControl("txtPaid")).Text) );
                        if (hdnCardCode == null || string.IsNullOrEmpty(hdnCardCode.Value)) // payment foreach vehicle/ accessory
                        {
                            txtCustRemain.Text = GF.FormatNumeric((dblPaid + TotalPayment).ToString(), "SumDec");
                            rupdate[0]["Paid"] = 0;
                            rupdate[0]["Remain"] = GF.FormatNumeric(GF.ResetFormatNumeric(dblRemain.ToString()), "SumDec");
                        }
                        else // Customer remain amount
                        {
                            foreach (DataRow dr in tblRDR1.Rows)
                            {
                                if (!string.IsNullOrEmpty(dr["CardCode"].ToString())) continue;
                                if ((bool)dr["Selected"])
                                {
                                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls de-selection all payments before de-selection this remain.');", true);
                                    ((CheckBox)row.FindControl("chkSelected")).Checked = true;
                                    return;
                                }
                            }
                            rupdate[0]["Paid"] = 0;
                            rupdate[0]["Remain"] = GF.FormatNumeric(GF.ResetFormatNumeric(dblRemain.ToString()), "SumDec");
                            txtCustRemain.Text = GF.FormatNumeric((TotalPayment - dblPaid).ToString(), "SumDec");
                        }
                        
                    }
                    else // Selection payment
                    {
                        if (hdnCardCode == null || string.IsNullOrEmpty(hdnCardCode.Value))
                        {
                            if (TotalPayment <= 0)
                            {
                                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Total Paid Amount before selection payment');", true);
                                ((CheckBox)row.FindControl("chkSelected")).Checked = false;
                                txtCustRemain.Focus();
                                return;
                            }
                            CustRemainTemp = TotalPayment - dblRemain;
                            if (CustRemainTemp > 0)
                            {
                                rupdate[0]["Paid"] = dblRemain;
                                rupdate[0]["Remain"] = 0;
                                txtCustRemain.Text = GF.FormatNumeric(GF.ResetFormatNumeric(CustRemainTemp.ToString()), "SumDec");
                            }
                            else
                            {
                                rupdate[0]["Paid"] = GF.FormatNumeric(GF.ResetFormatNumeric(TotalPayment.ToString()), "SumDec");
                                rupdate[0]["Remain"] = GF.FormatNumeric((dblRemain - TotalPayment).ToString(), "SumDec");
                                txtCustRemain.Text = "0";
                            }
                        }
                        else // customer remain
                        {
                            rupdate[0]["Paid"] = GF.FormatNumeric(Math.Abs(dblRemain).ToString(), "SumDec");
                            rupdate[0]["Remain"] = 0;
                            txtCustRemain.Text = GF.FormatNumeric((TotalPayment + Math.Abs(dblRemain)).ToString(), "SumDec");
                        }
                        
                    }
                    rupdate[0]["Selected"] = ((CheckBox)row.FindControl("chkSelected")).Checked;
                }
            }
            BindData(tblRDR1);
            updateTableTotalPrice();
            CheckBox chkheader = (CheckBox)grvSO.HeaderRow.FindControl("chkheader");
            int count = 0;
            foreach (GridViewRow rowView in this.grvSO.Rows)
            {
                CheckBox chkChild = (CheckBox)rowView.FindControl("chkSelected");
                if (chkChild.Checked)
                {
                    count += 1;
                }
            }
            if (count < this.grvSO.Rows.Count)
            {
                chkheader.Checked = false;
            }
            else
            {
                chkheader.Checked = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void chkAllSelected_CheckedChanged(object sender, EventArgs e)
        {

            DataTable tblRDR1 = (DataTable)Session["TblRDR1Table"];
            CheckBox chkheader = (CheckBox)grvSO.HeaderRow.FindControl("chkheader");
            bool headerCheck = false;
            foreach (GridViewRow rowView in this.grvSO.Rows)
            {
                headerCheck = chkheader.Checked;
                CheckBox chkChild = (CheckBox)rowView.FindControl("chkSelected");
                HiddenField hdnRemainOrg = (HiddenField)rowView.FindControl("hdnRemainOrg");
                HiddenField hdnCardCode = (HiddenField)rowView.FindControl("hdnCardCode");
                Label lblNo = (Label)rowView.FindControl("lblNo");
                Double dblRemain = Double.Parse(string.IsNullOrEmpty(hdnRemainOrg.Value) ? "0" : GF.ResetFormatNumeric(hdnRemainOrg.Value));
                Double TotalPayment = Double.Parse(string.IsNullOrEmpty(txtCustRemain.Text.Trim()) ? "0" : GF.ResetFormatNumeric(txtCustRemain.Text.Trim()));
                Double CustRemainTemp = 0;
                DataRow[] rupdate = tblRDR1.Select("No='" + lblNo.Text.Trim() + "'");
                chkChild.Checked = chkheader.Checked;
            
                if (rupdate.Length > 0)
                {
                    if (chkChild.Checked == false)
                    {
                        Double dblPaid = Double.Parse(string.IsNullOrEmpty(((TextBox)rowView.FindControl("txtPaid")).Text) ? "0" : GF.ResetFormatNumeric(((TextBox)rowView.FindControl("txtPaid")).Text));
                        if (hdnCardCode == null || string.IsNullOrEmpty(hdnCardCode.Value)) // payment foreach vehicle/ accessory
                        {
                            txtCustRemain.Text = GF.FormatNumeric((dblPaid + TotalPayment).ToString(), "SumDec");
                            rupdate[0]["Paid"] = 0;
                            rupdate[0]["Remain"] = GF.FormatNumeric(GF.ResetFormatNumeric(dblRemain.ToString()), "SumDec");
                        }
                        else // Customer remain amount
                        {
                            foreach (DataRow dr in tblRDR1.Rows)
                            {
                                if (!string.IsNullOrEmpty(dr["CardCode"].ToString())) continue;
                                if ((bool)dr["Selected"])
                                {
                                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls de-selection all payments before de-selection this remain.');", true);
                                    chkChild.Checked = true;
                                    chkheader.Checked = true;
                                    return;
                                }
                            }
                            rupdate[0]["Paid"] = 0;
                            rupdate[0]["Remain"] = GF.FormatNumeric(GF.ResetFormatNumeric(dblRemain.ToString()), "SumDec");
                            txtCustRemain.Text = GF.FormatNumeric((TotalPayment - dblPaid).ToString(), "SumDec");
                        }

                    }
                    else
                    {
                        if (hdnCardCode == null || string.IsNullOrEmpty(hdnCardCode.Value))
                        {
                            if (TotalPayment <= 0)
                            {
                                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Total Paid Amount before selection payment');", true);
                                chkChild.Checked = false;
                                txtCustRemain.Focus();
                                chkheader.Checked = false;
                                return;
                            }
                            CustRemainTemp = TotalPayment - dblRemain;
                            if (CustRemainTemp > 0)
                            {
                                rupdate[0]["Paid"] = dblRemain;
                                rupdate[0]["Remain"] = 0;
                                txtCustRemain.Text = GF.FormatNumeric(GF.ResetFormatNumeric(CustRemainTemp.ToString()), "SumDec");
                            }
                            else
                            {
                                rupdate[0]["Paid"] = GF.FormatNumeric(GF.ResetFormatNumeric(TotalPayment.ToString()), "SumDec");
                                rupdate[0]["Remain"] = GF.FormatNumeric((dblRemain - TotalPayment).ToString(), "SumDec");
                                txtCustRemain.Text = "0";
                            }
                        }
                        else // customer remain
                        {
                            rupdate[0]["Paid"] = GF.FormatNumeric(Math.Abs(dblRemain).ToString(), "SumDec");
                            rupdate[0]["Remain"] = 0;
                            txtCustRemain.Text = GF.FormatNumeric((TotalPayment + Math.Abs(dblRemain)).ToString(), "SumDec");
                        }
                    }
                }
                rupdate[0]["Selected"] = chkheader.Checked;
            }
            BindData(tblRDR1);
            updateTableTotalPrice();
            chkheader = (CheckBox)grvSO.HeaderRow.FindControl("chkheader");
            chkheader.Checked = headerCheck;
        }
        protected void ChkRemain_CheckedChanged(object sender, EventArgs e)
        {

        }

        protected void txtPaymentAccount_TextChanged(object sender, EventArgs e)
        {
            updateTableTotalPrice();
        }
      
        protected void txtPaid_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtPaid = (TextBox)row.FindControl("txtPaid");
                Label lblRemain = (Label)row.FindControl("lblRemain");
                HiddenField hdnRemainOrg = (HiddenField)row.FindControl("hdnRemainOrg");

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tbRDR1 = (DataTable)Session["TblRDR1Table"];

                if (tbRDR1 != null && hdnRemainOrg != null && lblRemain != null)
                {
                    DataRow[] rupdate = tbRDR1.Select("No='" + lblNo.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Paid"] = GF.ResetFormatNumeric(txtPaid.Text.Trim()).Split('.')[0];
                        Double dblPaid =  Double.Parse( string.IsNullOrEmpty(GF.ResetFormatNumeric(txtPaid.Text.Trim())) ? "0" : txtPaid.Text.Trim());
                        Double dblRemainOrg = Double.Parse(string.IsNullOrEmpty(hdnRemainOrg.Value) ? "0" : GF.ResetFormatNumeric(hdnRemainOrg.Value));

                        lblRemain.Text = (dblRemainOrg - dblPaid).ToString();
                        
                        rupdate[0]["Remain"] = lblRemain.Text;
                        updateTableTotalPrice();
                    }
                }

                this.grvSO.EditIndex = -1;
                BindData(tbRDR1);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;            
            }
            txtRemarks.Focus();
        }

        protected void updateTableTotalPrice()
        {
            double orderTotal = 0.0;
            double paidTotal = 0.0;
            foreach (GridViewRow rowView in this.grvSO.Rows)
            {
                if (((CheckBox)rowView.FindControl("chkSelected")).Checked)
                {
                    //double total = GF.Object2Double((object)GF.ResetFormatNumeric(((Label)rowView.FindControl("lbTotalPaymets")).Text), "SumDec");
                    double total = Math.Abs(GF.Object2Double((object)GF.ResetFormatNumeric(((HiddenField)rowView.FindControl("hdnRemainOrg")).Value), "SumDec"));
                    orderTotal += total;
                    double paidAmnt = GF.Object2Double((object)GF.ResetFormatNumeric(((TextBox)rowView.FindControl("txtPaid")).Text), "SumDec");
                    paidTotal += paidAmnt;
                }
            }

            txtPaymentAccount.Text = GF.FormatNumeric(paidTotal.ToString(), "SumDec");
            //double paymentOnAcc = GF.Object2Double((object)GF.ResetFormatNumeric(string.IsNullOrEmpty(txtPaymentAccount.Text.Trim()) ? "0" : txtPaymentAccount.Text.Trim()), "SumDec");
            lblTotalAmountDue.Text = GF.FormatNumeric(orderTotal.ToString(), "SumDec");
            lblOpenBalance.Text = GF.FormatNumeric((paidTotal - orderTotal).ToString(), "SumDec");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dr"></param>
        private DataRow FillShipToAddress(string outletId, bool isFill)
        {
            try
            {
                if (outletId.Length > 0)
                {
                    MasterData obj = new MasterData();
                    DataSet tbWareHouse = null; //obj.GetWareHouseAddress(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode);
                    if (tbWareHouse != null && tbWareHouse.Tables.Count > 0)
                    {
                        DataRow[] r = tbWareHouse.Tables[0].Select("WhsCode = '" + outletId + "'");
                        if (r.Length > 0)
                        {
                            if (isFill)
                            {
                                StringBuilder shipTo = new StringBuilder();
                                shipTo.AppendLine(r[0]["Block"].ToString());
                                shipTo.AppendLine(r[0]["Street"].ToString() + " " + r[0]["City"].ToString());
                                shipTo.AppendLine(r[0]["Country"].ToString() + " " + r[0]["ZipCode"].ToString());
                            }
                            else return r[0];
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                    DataTable tblIncPmt = (DataTable)Session["IncPmtTable"];
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectBP":
                            ViewState["rowindex"] = -1;
                            this.lblError.Visible = false;
                            GridViewRow row = Session["ChosenBP"] != null ? (GridViewRow)Session["ChosenBP"] : null;
                            this.txtCustomerCode.Text = ((Label)row.FindControl("lblCardCode")).Text; 
                            this.txtCustomerName.Text = ((Label)row.FindControl("lblCardName")).Text;
                            this.txtCntctName.Text = ((Label)row.FindControl("lblCntctPrsn")).Text;
                            this.txtCustRemain.Text = GF.FormatNumeric(((Label)row.FindControl("lblRemain")).Text, "SumDec");
                            Session["ChosenBP"] = null;
                            break;

                        case "SelectDocList":
                            GridViewRow rowDocList = Session["ChosenDocList"] != null ? (GridViewRow)Session["ChosenDocList"] : null;
                            string incPmtId = ((Label)rowDocList.FindControl("lblDocNum")).Text;
                            LoadData(incPmtId, ((ulong)DocType.INCOMING).ToString());
                            break;

                        case "SelectAccount":
                            GridViewRow rowAccount = Session["ChosenAccount"] != null ? (GridViewRow)Session["ChosenAccount"] : null;
                            txtAccountCode.Text = ((Label)rowAccount.FindControl("lblAccountCode")).Text;
                            txtAccountName.Text = ((Label)rowAccount.FindControl("lblAcctName")).Text;
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        public String _collectData()
        {
            try
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                //Update table header
                DataTable dtHeader = new DataTable(TblHeaderName);
                dtHeader.Columns.Add("Series"); // 
                dtHeader.Columns.Add("DocType");

                dtHeader.Columns.Add("DocDate");
                dtHeader.Columns.Add("DocDueDate");
                dtHeader.Columns.Add("TaxDate");
                dtHeader.Columns.Add("CardCode");
                dtHeader.Columns.Add("CardName");
                dtHeader.Columns.Add("U_NumAtCard");
                dtHeader.Columns.Add("Comments");
                dtHeader.Columns.Add("BpAct");
                dtHeader.Columns.Add("PayNoDoc");
                dtHeader.Columns.Add("NoDocSum");
                dtHeader.Columns.Add("Address");

                if (ddlPaymentMeans.SelectedValue.Equals("C")) // Cash
                {
                    dtHeader.Columns.Add("CashAcct");
                    dtHeader.Columns.Add("CashSum");
                }
                else if (ddlPaymentMeans.SelectedValue.Equals("B")) // Bank Transfer
                {
                    dtHeader.Columns.Add("TrsfrAcct");
                    dtHeader.Columns.Add("TrsfrSum");
                }
                // UDF
                dtHeader.Columns.Add("U_ContactPerson");
                dtHeader.Columns.Add("U_DealerID");
                dtHeader.Columns.Add("U_Department");
                if (dbType == "VSM")
                {
                    dtHeader.Columns.Add("U_ACR");
                    dtHeader.Columns.Add("U_ACRDate");
                }
                DataRow drHeader = dtHeader.NewRow();
                drHeader["Series"] = 15;
                drHeader["DocType"] = "C";
                drHeader["DocDate"] = Utils.AppConstants.ConvertToDate(txtDueDate.Text).ToString("yyyyMMdd");
                drHeader["DocDueDate"] = Utils.AppConstants.ConvertToDate(txtDueDate.Text).ToString("yyyyMMdd");
                drHeader["TaxDate"] = Utils.AppConstants.ConvertToDate(txtDocDate.Text).ToString("yyyyMMdd");
                drHeader["Comments"] = txtRemarks.Text.Trim();
                drHeader["CardCode"] = txtCustomerCode.Text;
                drHeader["CardName"] = txtCustomerName.Text;
                drHeader["BpAct"] = "1311-10";
                drHeader["U_NumAtCard"] = txtSONo.Text.Trim();

                if (ddlPaymentMeans.SelectedValue.Equals("C")) // Cash
                {
                    drHeader["CashAcct"] = txtAccountCode.Text;
                    drHeader["CashSum"] = GF.Object2Double((object)GF.ResetFormatNumeric(txtPaymentAccount.Text), "SumDec");
                }
                else if (ddlPaymentMeans.SelectedValue.Equals("B")) // Bank Transfer
                {
                    drHeader["TrsfrAcct"] = txtAccountCode.Text;
                    drHeader["TrsfrSum"] = GF.Object2Double((object)GF.ResetFormatNumeric(txtPaymentAccount.Text), "SumDec");
                }

                drHeader["PayNoDoc"] = "Y";
                drHeader["NoDocSum"] = GF.Object2Double((object)GF.ResetFormatNumeric(txtPaymentAccount.Text), "SumDec");
                drHeader["Address"] = txtBillTo.Text.Trim();
                //UDF
                drHeader["U_ContactPerson"] = txtCntctName.Text.Trim();
                drHeader["U_DealerID"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                drHeader["U_Department"] = Utils.AppConstants.PARTS;
                if (dbType == "VSM")
                {
                    drHeader["U_ACR"] = this.txtPACR.Text;
                    drHeader["U_ACRDate"] = Utils.AppConstants.ConvertToDate(this.txtACRDate.Text).ToString("yyyyMMdd");
                }
                dtHeader.Rows.Add(drHeader);

                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");
                dtHeader.TableName = TblHeaderName;
                ds.Tables.Add(dtHeader.Copy());
                return objInfo.ToXMLStringFromDS(ConvertDocType.Get2String(DocType.INCOMING), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }

        private string BuildUpdateCustRemain()
        {
            DataTable dtBP = new DataTable("OCRD");
            dtBP.Columns.Add("DocEntry");
            dtBP.Columns.Add("U_Remain");
            DataRow drBP = dtBP.NewRow();
            drBP["DocEntry"] = txtCustomerCode.Text;
            drBP["U_Remain"] = (double.Parse(GF.ResetFormatNumeric(lblOpenBalance.Text)) < 0 ? "0" : GF.ResetFormatNumeric(lblOpenBalance.Text));
            dtBP.Rows.Add(drBP);
            DocumentXML objInfo = new DocumentXML();
            DataSet ds = new DataSet("DS");
            ds.Tables.Add(dtBP.Copy());

            return objInfo.ToXMLStringFromDS(ConvertDocType.Get2String(DocType.BUSINESS_PARTNER), ds);
        }

        private DataTable BuildContents(DataTable dtContent)
        {
            DataTable dt = new DataTable(TblLineName);
            dt.Columns.Add("No");
            DataColumn dcSelected = new DataColumn("Selected");
            dcSelected.DataType = Type.GetType("System.Boolean");
            dt.Columns.Add(dcSelected);
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Product");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("unitMsr");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("PriceBefDi");
            dt.Columns.Add("DiscPrcnt");
            dt.Columns.Add("Price");
            dt.Columns.Add("LineTotal");
            dt.Columns.Add("ShipDate");            
            dt.Columns.Add("DocEntry");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("SumApplied");
            dt.Columns.Add("Paid");
            dt.Columns.Add("Remain");
            dt.Columns.Add("Remain_Org");
            dt.Columns.Add("NumAtCard");
            dt.Columns.Add("CardCode");
            dt.Columns.Add("U_Discount");
            dt.Columns.Add("U_IncentiveDiscount");
            dt.Columns.Add("VatGroup");
            dt.Columns.Add("VatPrcnt");
            dt.Columns.Add("VatSum");
            dt.Columns.Add("U_BaseLine");

            if (dtContent != null)
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                DataRow row = null;
                bool lbIsAccessories = false;
                foreach (DataRow dr in dtContent.Rows)
                {
                    lbIsAccessories = GF.GetItemGroupByCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), dr["ItemCode"].ToString()).Equals("104");
                    string lsQty = dr["Quantity"].ToString();
                    int liQty = int.Parse(string.IsNullOrEmpty(lsQty) ? "0" : lsQty.Split('.')[0]);
                    //if (liQty <= 1 || lbIsAccessories)
                    {
                        
                        row = dt.NewRow();
                        row["No"] = (dt.Rows.Count + 1).ToString();
                        row["Selected"] = dr["Selected"].GetType().ToString().Equals("System.Int32") ? (dr["Selected"].ToString().Equals("1") ? true : false) : (bool)dr["Selected"];
                        row["U_Model"] = dr["U_Model"];
                        row["U_Product"] = dr["U_Product"];
                        row["U_Color"] = dr["U_Color"];
                        row["ItemCode"] = dr["ItemCode"];
                        row["Dscription"] = dr["Dscription"];
                        int index = Utils.AppConstants.GetColumnIndexByName(this.grvSO, "UoM");
                        if (dtContent.Columns.Contains("unitMsr"))
                        {
                            row["unitMsr"] = dr["unitMsr"];
                            if (index != -1)
                            {
                                this.grvSO.Columns[index].Visible =true;
                            }
                        }
                        else
                        {
                          
                            if (index != -1)
                            {
                                this.grvSO.Columns[index].Visible = false;
                            }
                        }
                        row["Quantity"] = GF.FormatNumeric(dr["Quantity"].ToString(), "QtyDec");
                        row["PriceBefDi"] = GF.FormatNumeric(dr["PriceBefDi"].ToString(), "PriceDec");
                        row["DiscPrcnt"] = GF.FormatNumeric(dr["DiscPrcnt"].ToString(), "PercentDec");
                        row["Price"] = GF.FormatNumeric(dr["Price"].ToString(), "PriceDec");
                        row["ShipDate"] = dr["ShipDate"];
                        row["LineTotal"] = GF.FormatNumeric(dr["LineTotal"].ToString(), "SumDec");

                        row["DocEntry"] = string.Empty;
                        row["LineNum"] = dr["LineNum"];
                        row["SumApplied"] = GF.FormatNumeric(dr["SumApplied"].ToString(), "SumDec");

                        row["Paid"] = GF.FormatNumeric(dr["Paid"].ToString(), "SumDec");
                        row["Remain"] = GF.FormatNumeric(dr["Remain"].ToString(), "SumDec");
                        row["Remain_Org"] = dr["Remain_Org"];
                        row["NumAtCard"] = txtSONo.Text.Trim();
                        row["CardCode"] = dr["CardCode"];

                        row["U_Discount"] = dr["U_Discount"].ToString().Length > 0 ? dr["U_Discount"].ToString() : "0";
                        row["U_IncentiveDiscount"] = dr["U_IncentiveDiscount"].ToString().Length>0 ? dr["U_IncentiveDiscount"].ToString():"0";
                        row["VatGroup"] = dr["VatGroup"];
                        row["VatPrcnt"] = dr["VatPrcnt"].ToString().Length > 0 ? dr["VatPrcnt"].ToString() : "0"; 
                        row["VatSum"] = dr["VatSum"].ToString().Length > 0 ? dr["VatSum"].ToString() : "0"; 
                        row["U_BaseLine"] = dr["U_BaseLine"];

                        dt.Rows.Add(row);
                    }
                    //else if (liQty > 1)
                    //{
                    //    for (int i = 0; i < liQty; i++)
                    //    {
                    //        row = dt.NewRow();
                    //        row["No"] = (dt.Rows.Count + 1).ToString();
                    //        row["Selected"] = (dr["Selected"].ToString().Equals("0") ? false : true);
                    //        row["U_Model"] = dr["U_Model"];
                    //        row["U_Product"] = dr["U_Product"];
                    //        row["U_Color"] = dr["U_Color"];
                    //        row["ItemCode"] = dr["ItemCode"];
                    //        row["Dscription"] = dr["Dscription"];
                    //        row["Quantity"] = 1;//GF.FormatNumeric(dr["Quantity"].ToString(), "QtyDec");
                    //        row["PriceBefDi"] = GF.FormatNumeric(dr["PriceBefDi"].ToString(), "PriceDec");

                    //        row["DiscPrcnt"] = GF.FormatNumeric(dr["DiscPrcnt"].ToString(), "PercentDec");
                    //        row["Price"] = GF.FormatNumeric(dr["Price"].ToString(), "PriceDec");
                    //        row["ShipDate"] = dr["ShipDate"];

                    //        row["LineTotal"] = GF.FormatNumeric((double.Parse(GF.ResetFormatNumeric(dr["LineTotal"].ToString())) / liQty).ToString(), "SumDec");
                    //        row["DocEntry"] = string.Empty;
                    //        row["LineNum"] = dr["LineNum"];
                    //        row["SumApplied"] = GF.FormatNumeric((double.Parse(GF.ResetFormatNumeric(dr["SumApplied"].ToString())) / liQty).ToString(), "SumDec");
                    //        row["Paid"] = GF.FormatNumeric((double.Parse(GF.ResetFormatNumeric(dr["Paid"].ToString())) / liQty).ToString(), "SumDec");
                    //        row["Remain"] = GF.FormatNumeric((double.Parse(GF.ResetFormatNumeric(dr["Remain"].ToString())) / liQty).ToString(), "SumDec");
                    //        row["Remain_Org"] = GF.FormatNumeric((double.Parse(GF.ResetFormatNumeric(dr["Remain_Org"].ToString())) / liQty).ToString(), "SumDec");
                    //        row["NumAtCard"] = txtSONo.Text.Trim();
                    //        row["CardCode"] = dr["CardCode"];
                    //        row["U_Discount"] = dr["U_Discount"];
                    //        row["U_IncentiveDiscount"] = dr["U_IncentiveDiscount"];
                    //        row["VatGroup"] = dr["VatGroup"];
                    //        row["VatPrcnt"] = dr["VatPrcnt"];
                    //        row["VatSum"] = dr["VatSum"];
                    //        row["U_BaseLine"] = dr["U_BaseLine"];

                    //        dt.Rows.Add(row);                        
                    //    }
                    //}
                }
            }
            return dt;
        }

        private DataTable BuildToSave(DataTable dtContent)
        {
            Double dblTotalPayment = Double.Parse((string.IsNullOrEmpty(txtCustRemain.Text) ? "0" : txtCustRemain.Text.Trim()));

            DataTable dt = new DataTable(TblLineName);
            DataRow row = null;

            dt.Columns.Add("No");
            DataColumn dcSelected = new DataColumn("Selected");
            dcSelected.DataType = Type.GetType("System.Boolean");
            dt.Columns.Add(dcSelected);
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Product");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("PriceBefDi");
            dt.Columns.Add("DiscPrcnt");
            dt.Columns.Add("Price");
            dt.Columns.Add("LineTotal");
            dt.Columns.Add("ShipDate");
            dt.Columns.Add("DocEntry");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("SumApplied");
            dt.Columns.Add("Paid");
            dt.Columns.Add("Remain");
            dt.Columns.Add("Remain_Org");
            dt.Columns.Add("NumAtCard");
            dt.Columns.Add("CardCode");
            dt.Columns.Add("U_Discount");
            dt.Columns.Add("U_IncentiveDiscount");
            dt.Columns.Add("VatGroup");
            dt.Columns.Add("VatPrcnt");
            dt.Columns.Add("VatSum");
            dt.Columns.Add("U_BaseLine");

            if (dtContent != null)
            {
                foreach (DataRow dr in dtContent.Rows)
                {
                    if (!(bool)dr["Selected"] && !string.IsNullOrEmpty(dr["CardCode"].ToString())) continue;
                    row = dt.NewRow();
                    row["No"] = dr["No"];
                    row["Selected"] = (bool)dr["Selected"];
                    row["U_Model"] = dr["U_Model"];
                    row["U_Product"] = dr["U_Product"];
                    row["U_Color"] = dr["U_Color"];
                    row["ItemCode"] = dr["ItemCode"];
                    row["Dscription"] = dr["Dscription"];
                    row["Quantity"] = GF.ResetFormatNumeric(dr["Quantity"].ToString());
                    row["PriceBefDi"] = GF.ResetFormatNumeric(dr["PriceBefDi"].ToString());
                    row["DiscPrcnt"] = GF.ResetFormatNumeric(dr["DiscPrcnt"].ToString());
                    row["Price"] = GF.ResetFormatNumeric(dr["Price"].ToString());
                    row["ShipDate"] = dr["ShipDate"];
                    row["LineTotal"] = GF.ResetFormatNumeric(dr["LineTotal"].ToString());

                    row["DocEntry"] = string.Empty;
                    row["LineNum"] = dr["LineNum"];
                    row["SumApplied"] = GF.ResetFormatNumeric(dr["SumApplied"].ToString());
                    row["Paid"] = GF.ResetFormatNumeric(dr["Paid"].ToString());
                    row["Remain"] = GF.ResetFormatNumeric(dr["Remain"].ToString());
                    row["Remain_Org"] = dr["Remain_Org"];
                    row["NumAtCard"] = txtSONo.Text.Trim();
                    row["CardCode"] = row["Quantity"].ToString().Equals("0") ? txtCustomerCode.Text : "";

                    row["U_Discount"] = dr["U_Discount"];
                    row["U_IncentiveDiscount"] = dr["U_IncentiveDiscount"];
                    row["VatGroup"] = dr["VatGroup"];
                    row["VatPrcnt"] = dr["VatPrcnt"];
                    row["VatSum"] = dr["VatSum"];
                    row["U_BaseLine"] = dr["U_BaseLine"];

                    dt.Rows.Add(row);
                }
            }
            if (dblTotalPayment > 0)
            {
                row = dt.NewRow();
                row["No"] = "0";
                row["Selected"] = false;
                row["U_Model"] = string.Empty;
                row["U_Product"] = string.Empty;
                row["U_Color"] = string.Empty;
                row["ItemCode"] = string.Empty;
                row["Dscription"] = "Remain";
                row["Quantity"] = 0;
                row["PriceBefDi"] = 0;
                row["DiscPrcnt"] = 0;
                row["Price"] = 0;
                row["ShipDate"] = DateTime.Now.ToString("MM/dd/yyyy");
                row["LineTotal"] = 0;

                row["DocEntry"] = string.Empty;
                row["LineNum"] = 0;
                row["SumApplied"] = 0;
                row["Paid"] = 0;
                row["Remain"] = (dblTotalPayment * -1);
                row["Remain_Org"] = 0;
                row["NumAtCard"] = string.Empty;//txtSONo.Text.Trim();
                row["CardCode"] = txtCustomerCode.Text;

                row["U_Discount"] = 0;
                row["U_IncentiveDiscount"] = 0;
                row["VatGroup"] = string.Empty;
                row["VatPrcnt"] = 0;
                row["VatSum"] = 0;
                row["U_BaseLine"] = 0;

                dt.Rows.Add(row);
            }

            return dt;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtCustomerCode.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Business Partner','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    return;
                }

                if ( (string.IsNullOrEmpty(txtPaymentAccount.Text) || double.Parse(txtPaymentAccount.Text) <= 0 ))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Confirmation Amount must be greater than zero','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    return;
                }

                if( string.IsNullOrEmpty(txtAccountCode.Text) )
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Payment Account is not defined','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    return;
                }

                if(string.IsNullOrEmpty(txtSONo.Text.Trim()))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Sale Order is not be empty.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    return;                
                }

                String requestXML = _collectData();
                if (requestXML == "") return;

                string UpdateRemain = BuildUpdateCustRemain();

                DataTable tblRDR1 = (DataTable)Session["TblRDR1Table"];

                tblRDR1 = BuildToSave(tblRDR1);

                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                Transaction ts = new Transaction();
                DataSet ds = ts.CreateAdvanvePayment(dbType, requestXML, "", tblRDR1, UpdateRemain, txtCustomerCode.Text);

                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);

                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseCancel(true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
            CloseCancel(false);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isClose"></param>
        private void CloseCancel(bool isClose)
        {
            try
            {
                Transaction obj = new Transaction();
                string error = string.Empty;
                //if (_isPO == "1")
                //{
                //    //error = obj.CloseCancelPO(int.Parse(_docEntry), _companyCode, isClose, false);
                //}
                //else
                //{
                //    //error = obj.CloseCancelPO(int.Parse(_docEntry), _companyCode, isClose, true);
                //}
                //if (error.Length == 0)
                //{
                //    this.lblError.Text = "Operation complete successful!";
                //    DisableControl();
                //}
                //else
                //{
                //    this.lblError.Text = error;
                //}
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;
        }

        protected void LoadData(String incPmtId, string NewDocType)
        {
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            Transaction ts = new Transaction();
            DataSet returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, incPmtId, dbType);
            DataTable dtHeader = null;

            if (returnDoc == null) returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, "1", dbType);

            if (returnDoc == null || returnDoc.Tables.Count < 1)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('No record found!','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return;
            }

            dtHeader = returnDoc.Tables[0];
            DataRow dr = dtHeader.Rows[0];

            this.txtIncNo.Text = dr["DocEntry"].ToString();
            this.txtCustomerCode.Text = dr["CardCode"].ToString();
            this.txtCustomerName.Text = dr["CardName"].ToString();
            this.txtCntctName.Text = dr["U_ContactPerson"].ToString();
            this.txtSONo.Text = dr["U_NumAtCard"].ToString();
            if (dbType == "VSM")
            {
                this.txtPACR.Text = dr["U_ACR"].ToString();
                this.txtACRDate.Text = dr["U_ACRDate"].ToString();
            }
            LoadVSMSONumber();

            GetDefault getDefault = new GetDefault();

            if (!String.IsNullOrEmpty(dr["CashAcct"].ToString())) // Cash
            {
                ddlPaymentMeans.SelectedValue = "C";
                txtAccountCode.Text = dr["CashAcct"].ToString();
                txtAccountName.Text = getDefault.GetAccountNameByCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), dr["CashAcct"].ToString());
            }
            else // Bank Transfer
            {
                ddlPaymentMeans.SelectedValue = "B";
                txtAccountCode.Text = dr["TrsfrAcct"].ToString();
                txtAccountName.Text = getDefault.GetAccountNameByCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), dr["TrsfrAcct"].ToString());
            }

            txtPostingDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDate"], new CultureInfo("es-US")));
            txtDocDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["TaxDate"], new CultureInfo("es-US")));
            txtDueDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dtHeader.Rows[0]["DocDueDate"], new CultureInfo("es-US")));

            txtRemarks.Text = dr["Comments"].ToString();
            txtPaymentAccount.Text = GF.FormatNumeric(dr["DocTotal"].ToString(), "SumDec");
           
            if (NewDocType != ((ulong)DocType.INCOMING).ToString())
                SetScreenStatus("New");
            else SetScreenStatus("Update");
            // Load details data
            LoadRDR1(incPmtId, "tbl_RDR1");
        }

        protected void LoadDefault()
        {
            this.txtPostingDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDueDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDocDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtIncNo.Text = 
            this.txtCntctName.Text = 
            this.txtBillTo.Text = 
            this.txtCustomerCode.Text = 
            this.txtCustomerName.Text = 
            this.txtAccountCode.Text = 
            this.txtAccountName.Text = string.Empty;

            LoadRDR1("0", "tbl_RDR1");
        }

        protected void LoadRDR1(String incPmtId, string TableLineName)
        {
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            DataTable dtRDR1 = GF.GetTblRDR1(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), incPmtId, TableLineName);
            dtRDR1 = BuildContents(dtRDR1);
            BindData(dtRDR1);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            Session["TblRDR1Table"] = tblData;
            this.grvSO.DataSource = tblData;
            this.grvSO.DataBind();
        }

        protected void ClearScreen()
        {
            CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;

            txtPostingDate.Text.ToString(ci);
            txtDueDate.Text.ToString(ci);
            txtDocDate.Text.ToString(ci);
            txtCustomerCode.Text =
            txtCustomerName.Text =
            txtRemarks.Text =
            txtCntctName.Text =
            txtAccountCode.Text =
            txtAccountName.Text = 
            txtSONo.Text = string.Empty;
            txtCustRemain.Text = "0";
            ddlPaymentMeans.SelectedIndex = 0;

            DataTable dt = new DataTable(TblLineName);
            dt.Columns.Add("No");
            DataColumn dcSelected = new DataColumn("Selected");
            dcSelected.DataType = Type.GetType("System.Boolean");
            dt.Columns.Add(dcSelected);
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Product");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("PriceBefDi");
            dt.Columns.Add("DiscPrcnt");
            dt.Columns.Add("Price");
            dt.Columns.Add("LineTotal");
            dt.Columns.Add("ShipDate");
            dt.Columns.Add("DocEntry");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("SumApplied");
            dt.Columns.Add("Paid");
            dt.Columns.Add("Remain");
            dt.Columns.Add("Remain_Org");
            dt.Columns.Add("NumAtCard");
            BindData(dt);
            SetScreenStatus("New");
        }

        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    btnSave.Enabled = 
                    btnCancel.Enabled =
                    btnGLAccount.Enabled = 
                    btnFindSO.Enabled = true;
                    hdnIsUpdate.Value = "false";
                    this.ddlPaymentMeans.SelectedValue = "B";
                    btnGLAccount.Visible = false;
                    txtAccountCode.Text = "1121-01";
                    txtAccountName.Text = "Cash in Bank - Calyon Bank (Tiền gửi NH Calyon Bank (VND))";
                    hdnStatus.Value = "O";
                    break;

                case "Update":
                    btnGLAccount.Enabled =
                    btnFindSO.Enabled = 
                    btnSave.Enabled = 
                    btnCancel.Enabled = false;
                    hdnIsUpdate.Value = "false";
                    hdnStatus.Value = "C";
                    break;

                case "Close":
                    btnSave.Enabled = 
                    btnCancel.Enabled =
                    btnGLAccount.Enabled =
                    btnFindSO.Enabled = 
                    btnGLAccount.Enabled = false;
                    hdnStatus.Value = "C";
                    break;
            }
        }

        protected void ddlPaymentMeans_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (((DropDownList)sender).SelectedValue.Equals("C"))
            {
                btnGLAccount.Visible = false;
                txtAccountCode.Text = "1111-00";
                txtAccountName.Text = "Cash on hand - VND (Tiền VND)";
            }
            else
            {
                btnGLAccount.Visible = false;
                txtAccountCode.Text = "1121-01";
                txtAccountName.Text = "Cash in Bank - Calyon Bank (Tiền gửi NH Calyon Bank (VND))";
            }
        }

        protected void btnLastRecord_Click(object sender, EventArgs e)
        {
            GetDefault fGetDefault = new GetDefault();
            string lsAdvNo = fGetDefault.GetMaxDocEntry
            (
                Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER, 
                Session[Utils.AppConstants.ID_Dealer].ToString(), 
                Utils.AppConstants.PARTS,
                ConvertDocType.Get2String(DocType.INCOMING) + " and PayNoDoc = 'Y' ", 
                TblHeaderName, HeaderKeyName
            );
            if (txtIncNo.Text.CompareTo(lsAdvNo) != 0) Response.Redirect(CurrentPageUrl + "?incPmt_id=" + lsAdvNo);
        }

        protected void btnFindSO_Click(object sender, EventArgs e)
        {
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

            if ( string.IsNullOrEmpty(txtCustomerCode.Text.Trim()))
            {
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls select a customer, first.');", true);
                return;
            }
            else if (string.IsNullOrEmpty(txtSONo.Text.Trim()))
            {
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input a Sale Order.');", true);
                return;
            }
            else
            {
                string lsValidSO = GF.GetSingleValue(dbType, "select DocEntry from ORDR where CardCode = '" + txtCustomerCode.Text.Trim() + "' and DocEntry = " + txtSONo.Text.Trim(), "DocEntry");
                if (string.IsNullOrEmpty(lsValidSO.Trim()))
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Invalid Sale Order.');", true);
                    return;
                }
            }
            
            DataTable dtRDR1 = GF.GetTblRDR1RemainAmnt(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), txtSONo.Text.Trim());
            string lsSO = GF.GetSingleValue(dbType, "select COUNT(*) As NumAtCard from tbl_RDR1 where NumAtCard = " + txtSONo.Text.Trim(), "NumAtCard");

            if (dtRDR1 != null && dtRDR1.Rows.Count > 0) dtRDR1 = BuildContents(dtRDR1);
            else if (lsSO.Equals("0"))
            {
                dtRDR1 = GF.GetTblRDR1(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), txtSONo.Text.Trim(), "RDR1");
                dtRDR1 = BuildContents(dtRDR1);
            }

            //Group Item

            DataTable tbTemp = dtRDR1.Clone();
            foreach (DataRow rGroup in dtRDR1.Rows)
            {
                DataRow[] rCheck = tbTemp.Select("ItemCode='" + rGroup["ItemCode"].ToString() + "'");
                if (rCheck.Length > 0)
                {
                    double quantity = double.Parse(rCheck[0]["Quantity"].ToString());
                    quantity += double.Parse(rGroup["Quantity"].ToString());
                    rCheck[0]["Quantity"] = GF.FormatNumeric(quantity.ToString(), "SumDec"); 
                    double Remain = double.Parse(rCheck[0]["Remain"].ToString());
                    Remain += double.Parse(rGroup["Remain"].ToString());
                    rCheck[0]["Remain"] = GF.FormatNumeric(Remain.ToString(), "SumDec"); 
                    double Remain_Org = double.Parse(rCheck[0]["Remain_Org"].ToString());
                    Remain_Org += double.Parse(rGroup["Remain_Org"].ToString());
                    rCheck[0]["Remain_Org"] = GF.FormatNumeric(Remain_Org.ToString(), "SumDec"); 
                    double Paid = double.Parse(rCheck[0]["Paid"].ToString());
                    Paid += double.Parse(rGroup["Paid"].ToString());
                    rCheck[0]["Paid"] = GF.FormatNumeric(Paid.ToString(), "SumDec"); 
                    double LineTotal = double.Parse(rCheck[0]["LineTotal"].ToString());
                    LineTotal += double.Parse(rGroup["LineTotal"].ToString());
                    rCheck[0]["LineTotal"] = GF.FormatNumeric(LineTotal.ToString(), "SumDec"); 
                    double U_Discount = double.Parse(rCheck[0]["U_Discount"].ToString());
                    U_Discount += double.Parse(rGroup["U_Discount"].ToString());
                    rCheck[0]["U_Discount"] = GF.FormatNumeric(U_Discount.ToString(), "SumDec"); 
                    double U_IncentiveDiscount = double.Parse(rCheck[0]["U_IncentiveDiscount"].ToString());
                    U_IncentiveDiscount += double.Parse(rGroup["U_IncentiveDiscount"].ToString());
                    rCheck[0]["U_IncentiveDiscount"] = GF.FormatNumeric(U_IncentiveDiscount.ToString(), "SumDec"); 
                    double SumApplied = double.Parse(rCheck[0]["SumApplied"].ToString());
                    SumApplied += double.Parse(rGroup["SumApplied"].ToString());
                    rCheck[0]["SumApplied"] = GF.FormatNumeric(SumApplied.ToString(), "SumDec"); 
                }
                else
                {
                    tbTemp.ImportRow(rGroup);
                }
            }
            dtRDR1 = tbTemp.Copy();

            // Get Customer Remain
            if (dtRDR1 != null && dtRDR1.Rows.Count > 0)
            {
                DataTable dtCustRemain = GF.GetCustRemainAmt(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), txtCustomerCode.Text);
                if (dtCustRemain != null && dtCustRemain.Rows.Count == 1)
                {
                    DataRow row = dtRDR1.NewRow();
                    row["No"] = dtCustRemain.Rows[0]["No"];
                    row["Selected"] = dtCustRemain.Rows[0]["Selected"];
                    row["U_Model"] = 
                    row["U_Product"] = 
                    row["U_Color"] = 
                    row["ItemCode"] = string.Empty;
                    row["Dscription"] = dtCustRemain.Rows[0]["Dscription"];

                    row["Quantity"] =
                    row["PriceBefDi"] =
                    row["DiscPrcnt"] =
                    row["Price"] = 0;
                    row["ShipDate"] = dtCustRemain.Rows[0]["ShipDate"];
                    row["LineTotal"] = 0;
                    row["DocEntry"] = string.Empty;
                    row["LineNum"] = 
                    row["SumApplied"] = 
                    row["Paid"] = 0;
                    row["Remain"] = GF.FormatNumeric(dtCustRemain.Rows[0]["Remain"].ToString(), "SumDec");
                    row["Remain_Org"] = dtCustRemain.Rows[0]["Remain_Org"];
                    row["NumAtCard"] = dtCustRemain.Rows[0]["NumAtCard"];
                    row["CardCode"] = txtCustomerCode.Text;

                    row["U_Discount"] =
                    row["U_IncentiveDiscount"] = 
                    row["VatPrcnt"] = 
                    row["VatSum"] = 
                    row["U_BaseLine"] = 0;
                    row["VatGroup"] = string.Empty;

                    dtRDR1.Rows.InsertAt(row, 0);
                }
            }
            BindData(dtRDR1);
        }

        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvSO.PageIndex = e.NewPageIndex;
            DataTable tblRDR1 = (DataTable)Session["TblRDR1Table"];
            BindData(tblRDR1);
        }

        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                if (this.hdnStatus.Value == "C")
                {
                    LinkButton lnkDelete = (LinkButton)myRow.FindControl("lnkDelete");
                    if (lnkDelete != null) lnkDelete.Enabled = false;

                    CheckBox chkSelected = (CheckBox)myRow.FindControl("chkSelected");
                    if (chkSelected != null) chkSelected.Enabled = false;
                }
            }
        }

        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";

                Label lblRemain = (Label)e.Row.FindControl("lblRemain");
                TextBox txtPaid = (TextBox)e.Row.FindControl("txtPaid");
                CheckBox chkSelected = (CheckBox)e.Row.FindControl("chkSelected");

                if (lblRemain != null && txtPaid != null)
                {
                    if (string.IsNullOrEmpty(lblRemain.Text) || double.Parse(lblRemain.Text) == 0 || !chkSelected.Checked)
                    {
                        txtPaid.ReadOnly = true;
                        txtPaid.BackColor = System.Drawing.Color.Transparent;
                        txtPaid.BorderStyle = BorderStyle.None;
                    }
                }
            }
        }

        protected void txtSONo_TextChanged(object sender, EventArgs e)
        {
            LoadVSMSONumber();
        }

        private void LoadVSMSONumber()
        {
            if (string.IsNullOrEmpty(txtSONo.Text.Trim())) return;
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

            string lsValidSO = GF.GetSingleValue(dbType, "select DocEntry from ORDR where CardCode = '" + txtCustomerCode.Text.Trim() + "' and DocEntry = " + txtSONo.Text.Trim(), "DocEntry");
            if (string.IsNullOrEmpty(lsValidSO.Trim()))
            {
                DataTable dtContents = BuildContents(null);
                BindData(dtContents);
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Invalid Sale Order.');", true);
                txtSONo.Focus();
                return;
            }
            else
            {
                lsValidSO = GF.GetSingleValue(dbType, "select * from ORDR where CardCode = '" + txtCustomerCode.Text.Trim() + "' and DocEntry = " + txtSONo.Text.Trim(), "U_SONBR");
                this.txtSONumber.Text = lsValidSO;
            }
        }
        protected void txtSONumber_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtSONumber.Text.Trim())) return;
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

            string lsValidSO = GF.GetSingleValue(dbType, "select * from ORDR where CardCode = '" + txtCustomerCode.Text.Trim() + "' and U_SONBR = '" + txtSONumber.Text.Trim() + "'", "DocEntry");
            if (string.IsNullOrEmpty(lsValidSO.Trim()))
            {
                DataTable dtContents = BuildContents(null);
                BindData(dtContents);
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Invalid Sale Order.');", true);
                txtSONo.Focus();
                return;
            }
            else
            {
                lsValidSO = GF.GetSingleValue(dbType, "select * from ORDR where CardCode = '" + txtCustomerCode.Text.Trim() + "' and U_SONBR = '" + this.txtSONumber.Text.Trim() + "'", "DocEntry");
                this.txtSONo.Text = lsValidSO;
            }
        }
        protected void txtCustRemain_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtCustRemain.Text)) return;
            txtCustRemain.Text = GF.FormatNumeric(txtCustRemain.Text, "SumDec");
        }

    }
}